//
//  AutomationController.swift
//  home
//
//  Created by Yun Zeng on 2019/8/5.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit

class AutomationController: UIViewController {

    lazy var customBarView: AutomationCustomBarView = {
        return AutomationCustomBarView()
    } ()
    
    lazy var contentsView: UIScrollView = {
        return UIScrollView()
    } ()
    
    lazy var largeTitleView: AutoLargeTitleView = {
        return AutoLargeTitleView(frame: .zero)
    } ()
    
    lazy var automationsView: UITableView = {
        let table =  UITableView()
        return table
    } ()
    
    private var automations =  [HomeAutomation]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initNavigationBar()
        
        let containerView = UIView()
        containerView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(containerView)

        containerView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        containerView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        containerView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        containerView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true

        contentsView.translatesAutoresizingMaskIntoConstraints = false
        contentsView.showsHorizontalScrollIndicator = false
        contentsView.showsVerticalScrollIndicator = false
        
        containerView.addSubview(contentsView)
        containerView.addSubview(customBarView)
        
        contentsView.addSubview(largeTitleView)
        contentsView.addSubview(automationsView)
        
        contentsView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
        contentsView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
        contentsView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
        contentsView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
//        contentsView.backgroundColor = UIColor.gray

        self.customBarView.translatesAutoresizingMaskIntoConstraints = false
        self.customBarView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.customBarView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        self.customBarView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        self.customBarView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true

        
        largeTitleView.translatesAutoresizingMaskIntoConstraints = false
        largeTitleView.topAnchor.constraint(equalTo: contentsView.topAnchor).isActive = true
        largeTitleView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
        largeTitleView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
        largeTitleView.heightAnchor.constraint(equalToConstant: 84).isActive = true
        
        largeTitleView.title = "自动化"
        largeTitleView.desc = "响应位置和家居环境的变化"
        
        contentsView.alwaysBounceVertical = true
        automationsView.translatesAutoresizingMaskIntoConstraints = false
        automationsView.topAnchor.constraint(equalTo: largeTitleView.bottomAnchor, constant: 8).isActive = true
        automationsView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 15).isActive = true
        automationsView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -15).isActive = true
        automationsView.layer.cornerRadius = 12
        
        automationsView.isScrollEnabled = false
        automationsView.register(AutomationCell.self, forCellReuseIdentifier: AutomationCell.identifier)
        automationsView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "AutomationViewHeaderFooterView")
        automationsView.rowHeight = 64
                
        automationsView.indicatorStyle = .black
        automationsView.delegate = self
        automationsView.sectionFooterHeight = 8.0
        automationsView.sectionHeaderHeight = 8.0
        automationsView.dataSource = self
        automationsView.separatorStyle = .none
        automationsView.backgroundColor = UIColor(red: 242/255, green: 242/255, blue: 242/255, alpha: 1)
        guard let home = HomeManager.instance.current else {
            return
        }
        self.automations = home.automationManager.automations
        automationsView.heightAnchor.constraint(equalToConstant: CGFloat(self.automations.count) * 64 + 16.0).isActive = true
        contentsView.contentSize = CGSize(width: self.view.frame.width, height: CGFloat(self.automations.count) * 64 + 16.0 + 84 + 35)
        
        
        Logger.Info("automations: \(home.automationManager.automations.count)")
        for automation in home.automationManager.automations {
            Logger.Info("automation\(automation.title): \(automation.subtitle)")
        }
    }
}


extension AutomationController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return automations.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 8
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 8
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        Logger.Info("index select: \(indexPath)")
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "AutomationEditControllerID") as! AutomationEditController
        
        controller.automation = self.automations[indexPath.row]
        controller.modalPresentationStyle = .formSheet
        controller.preferredContentSize = CGSize(width: 375, height: 740)
        controller.isModalInPresentation = false
        
        self.navigationController?.present(controller, animated: true)
        self.automationsView.deselectRow(at: indexPath, animated: true)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: AutomationCell.identifier, for: indexPath) as! AutomationCell
        if indexPath.row == self.automations.count  - 1 {
            _ = cell.setAutomation(automation: self.automations[indexPath.row])
        } else {
            _ = cell.setAutomation(automation: self.automations[indexPath.row])
        }
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "AutomationViewHeaderFooterView")!
        cell.backgroundView = UIView()
        cell.backgroundView?.backgroundColor = UIColor(red: 242/255, green: 242/255, blue: 242/255, alpha: 1)
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "AutomationViewHeaderFooterView")!
        cell.backgroundView = UIView()
        cell.backgroundView?.backgroundColor = UIColor(red: 242/255, green: 242/255, blue: 242/255, alpha: 1)
        return cell
    }
    
}
